package com.dap.dubbo.rpc.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import com.dap.dubbo.rpc.config.RedisConfig;
import com.dap.dubbo.rpc.utils.ServiceRateLimiter;
import redis.clients.jedis.Jedis;

@Activate(group = Constants.CONSUMER)
public class RedisLimitFilter implements Filter {
    public static final String DUBBO_APPLICATION_KEY = "Application:";
    public static final String STRATEGY="redis";
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Jedis jedis = RedisConfig.getJedis();
        String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
        String strategy = jedis.get(DUBBO_APPLICATION_KEY+ application+":strategy" );
        if (jedis != null) {
            jedis.close();
        }
        if(STRATEGY.equals(strategy)){
            ServiceRateLimiter serviceRateLimiter=new ServiceRateLimiter(invoker,invocation);
            return  serviceRateLimiter.execute();
        }else{
            return invoker.invoke(invocation);
        }
    }


}
